#!/bin/bash

ECHO="echo -e"

# linux shell color support.
RED="\\033[31m"
GREEN="\\033[32m"
YELLOW="\\033[33m"
BLACK="\\033[0m"

function log() {
    $ECHO $*
}

function log_e() {
    $ECHO "\033[1;32m $* \033[0m"
}
function log_w() {
    $ECHO "\033[1;35m $* \033[0m"
}
function log_i() {
    $ECHO "\033[1;31m $* \033[0m"
}

function get_distro() {
	ARCH=$(uname -m | sed 's/x86_/amd/;s/i[3-6]86/x86/')

    O_OS=$(uname -s)

	if [ $ARCH == "amd64" ]; then
		T_ARCH="x86_64"
		WK_ARCH="amd64"
        B_ARCH="x64"
	else
		T_ARCH="i386"
		WK_ARCH="i386"
        B_ARCH="i386"
	fi

	if [ -f /etc/redhat-release ]; then
		OS="CentOS"
		OS_VER=`cat /etc/redhat-release | sed 's/Linux\ //g' | cut -d" " -f3 | cut -d. -f1`

	elif [ -f /etc/lsb-release ]; then
		. /etc/lsb-release
		OS=$DISTRIB_ID
		OS_VER=$DISTRIB_CODENAME

	elif [ -f /etc/debian_version ]; then
		. /etc/os-release
		OS="Debian"  # XXX or Ubuntu??
		OS_VER=$VERSION_ID
	fi

    if [ "$O_OS" == "Darwin" ]; then
        OS="$O_OS"
        OS_VER=$(uname -r)
    fi

	export OS=$OS
	export OS_VER=$OS_VER
	export ARCH=$ARCH
	export T_ARCH=$T_ARCH
	export WK_ARCH=$WK_ARCH
    export BUILD_DIR_NAME=$OS-$B_ARCH

    ## for compatible with previous define
    if [ "$OS" == "Ubuntu" -a "$B_ARCH" == "x64" ]; then
        export BUILD_DIR_NAME=$B_ARCH
    fi
	log_i "\t Work in $OS $OS_VER $ARCH BUILD_DIR_NAME: $BUILD_DIR_NAME"
}

get_distro

USER=`whoami`

[ "$USER" != "root" ] && SUDO=sudo

optuser=`ls -ld /opt | cut -d ' ' -f3`
[ "$optuser" != "$USER" ] && $SUDO chown -R $optuser:$optuser /opt

PS="ps ax"

case $OS in
    Ubuntu)
    ;;
    CentOS)
    ;;
    Darwin)
    ;;
    *)
         log_w "Unknow supported system"
         exit
    ;;
esac

function program_hasstart() {
    cnt=`$PS | grep $1 | grep -v grep | grep -v ps | grep -v bash | wc -l`
    return $cnt
}

function check_tools() {
    which apt &> /dev/null
    if [ $? -eq 0 ]; then
        INSTALL_TOOLS=apt
    else
        which apt-get &> /dev/null
        if [ $? -eq 0 ]; then
            INSTALL_TOOLS=apt-get
        else
            which yum &> /dev/null
            if [ $? -eq 0 ]; then
                INSTALL_TOOLS=yum
            fi
        fi
    fi
}

function install_tools() {
    tools=$*
    case $INSTALL_TOOLS in
    apt | apt-get | yum)
        $SUDO $INSTALL_TOOLS -y install $tools
    ;;
    esac
}

function extern_tools() {

    which libtoolize &> /dev/null
    if [ $? -gt 0 ]; then
        log "Install libtool ..."
        install_tools libtool
    fi
    which autoconf  &> /dev/null
    if [ $? -gt 0 ]; then
        log "install autoconf ..."
        install_tools autoconf
    fi
}

check_tools

